# For prerequisites running the following sample, visit https://help.aliyun.com/document_detail/xxxxx.html

import os
import requests
from http import HTTPStatus
import dashscope
from dashscope.audio.asr import *
import db
from datetime import datetime
import database
from dotenv import load_dotenv
import os
# 加载.env文件
load_dotenv()


def ok():
    dashscope.api_key = os.getenv("api_key_aliy")
    r = requests.get(
        "https://dashscope.oss-cn-beijing.aliyuncs.com/samples/audio/paraformer/hello_world_female2.wav"
    )
    with open("asr_example.wav", "wb") as f:
        f.write(r.content)

    # 存储识别和翻译结果的变量
    class ResultStorage:
        def __init__(self):
            self.transcription = None
            self.translation = None

    storage = ResultStorage()

    class Callback(TranslationRecognizerCallback):
        def on_open(self) -> None:
            print("TranslationRecognizerCallback open.")

        def on_close(self) -> None:
            print("TranslationRecognizerCallback close.")

        def on_event(
                self,
                request_id,
                transcription_result: TranscriptionResult,
                translation_result: TranslationResult,
                usage,
        ) -> None:
            print("request id: ", request_id)
            print("usage: ", usage)
            if translation_result is not None:
                print(
                    "translation_languages: ",
                    translation_result.get_language_list(),
                )
                english_translation = translation_result.get_translation("en")
                if english_translation:
                    storage.translation = english_translation.text  # 存储翻译结果
                    print("Translation:", storage.translation)
            if transcription_result is not None:
                storage.transcription = transcription_result.text  # 存储识别结果
                print("Transcription:", storage.transcription)

        def on_error(self, message) -> None:
            print('error: {}'.format(message))

        def on_complete(self) -> None:
            print('TranslationRecognizerCallback complete')

    callback = Callback()

    translator = TranslationRecognizerChat(
        model="gummy-chat-v1",
        format="wav",
        sample_rate=16000,
        callback=callback,
        translation_enabled=True,  # 关键：必须启用翻译
        translation_target_languages=["en"]
    )

    translator.start()

    try:
        with open("asr_example.wav", "rb") as f:
            while True:
                audio_data = f.read(12800)
                if not audio_data:
                    break
                if not translator.send_audio_frame(audio_data):
                    break
    finally:
        translator.stop()
        # 返回识别和翻译结果
    return {
        "transcription": storage.transcription,
        "translation": storage.translation,
    }
if __name__ == '__main__':
    dashscope.api_key = os.getenv("api_key_aliy")
    #print(ok())
    #
    # sql_select = "select * from question_option where `id` =1"
    # res1 = db.select(sql_select)

    #database类使用说明
    # 查询示例
    #user = database.query_one("SELECT * FROM question_option WHERE id = %s", (2,))
    # users = database.query_one("SELECT * FROM question_option WHERE id = 3")
    # all_users = database.query_all("SELECT * FROM question_option LIMIT 10")

    # 插入示例
    # new_id = database.insert("api_log", {
    #     "type": 1,
    #     "addtime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    # })
    # 更新示例
    # updated_rows = database.update(
    #     table="users",
    #     data={"username": "new_name", "email": "new@example.com"},
    #     condition="id = %s",
    #     condition_params=(new_id,)
    # )
    # # 删除示例
    # deleted_rows = database.delete("users", "id = %s", (new_id,))

    #事务
    # try:
    #     # 先查询当前记录数
    #     operations = [
    #         {
    #             'type': 'insert',
    #             'table': 'api_log',
    #             'data': {
    #                 "type": 25,  # 测试值
    #                 "addtime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    #             }
    #         },
    #         {
    #             'type': 'update',
    #             'table': 'api_log',
    #             'data': {"type": 22},  # 故意错误
    #             'condition': 'id = %s',
    #             'condition_params': (1,)
    #         }
    #     ]
    #     result = database.execute_transaction(operations)
    # except Exception as e:
    #     print(f"事务回滚成功！错误: {e}")
    #     print("测试通过：事务已正确回滚")
